package com.asset.dispoal.file.evidenceRecognition.service.commom;

import com.asset.dispoal.file.evidenceRecognition.dto.FileByZipRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.io.IOUtil;
import tech.mhuang.pacebox.core.util.ZipUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class DownloadFileByZipCommand implements BaseCommand<FileByZipRequest, Result> {

    @Autowired
    private Environment environment;

    @Override
    public Result<String> execute(FileByZipRequest request) {
        OutputStream os = null;
        String basePath;
        try {
            String docUrl = environment.getProperty("file.evidence.url");

            LocalDate now = LocalDate.now();
            String year = String.valueOf(now.getYear());
            String month = String.valueOf(now.getMonthValue());
            String day = String.valueOf(now.getDayOfMonth());
            basePath = "/custdownload/" + year + "/" + month + "/" + day + "/" + request.getContractNo() + request.getTypeName() + ".zip";

            File file = new File(docUrl + basePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            List<File> files = new ArrayList<>();

            for (String url : request.getFileUrlList()) {
                files.add(new File(docUrl + url));
            }

            os = Files.newOutputStream(file.toPath());
            ZipUtil.toZip(files, os);
            // 存入redis
            return Result.ok(basePath);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(500, e.getMessage());
        } finally {
            IOUtil.close(os);
        }
    }
}
